package com.wang.transfer.util.algorithm;

import java.math.BigDecimal;
import java.util.Arrays;

/**
 * 合并两个有序数组
 */
public class MergeSortArray {

    public static void main(String[] args) {
        int[] num1 = new int[]{1, 3, 5, 7, 9, 0, 0, 0, 0};
        int[] num2 = new int[]{2, 4, 6, 8};
//        System.out.println(Arrays.toString(merge(num1, 5, num2, 4)));
//        System.out.println(Arrays.toString(merge2(num1, 5, num2, 4)));
        // \u000d System.out.println("hha");
    }

    public static int[] merge(int[] num1, int m, int[] num2, int n) {
        int[] num = new int[m];
        System.arraycopy(num1, 0, num, 0, m);
        int i = 0, z = 0, j = 0;
        while (i < m && j < n) {
            num1[z++] = num[i] < num2[j] ? num[i++] : num2[j++];
        }
        if (i < m) {
            System.arraycopy(num, i, num1, i + j, m + n - i - j);
        } else if (j < n) {
            System.arraycopy(num2, j, num1, i + j, m + n - i - j);
        }
        return num1;
    }

    public static int[] merge2(int[] num1, int m, int[] num2, int n) {
        int i = m - 1, j = n - 1, l = m + n - 1;
        while (i >= 0 && j >= 0) {
            num1[l--] = num1[i] > num2[j] ? num1[i--] : num2[j--];
        }
        if (j > 0) {
            System.arraycopy(num2, 0, num1, 0, j);
        }
        return num1;
    }
}
